<template>
	<div>
		<el-dialog :title="'编辑卡权益' + '：' + name" :visible.sync="dialogVisible" :close-on-click-modal="false" fullscreen center @close="close">
			<el-form ref="form" v-loading="loading" :model="form" :rules="rules" class="content" label-width="120px" size="small">
				<!-- 消费折扣 -->
				<el-form-item label="消费折扣：" prop="categoryDiscount">
					<el-radio v-model="form.discountRadio" :label="1">无折扣</el-radio>
					<br />
					<div>
						<el-radio v-model="form.discountRadio" :label="2">消费享折扣&nbsp;&nbsp;</el-radio>
						<el-input v-model="form.categoryDiscount" :disabled="form.discountRadio === 1" maxlength="3" class="input-append-150">
							<template slot="append">
								折
							</template>
						</el-input>
						<el-switch v-if="superData.status == 1" v-model="form.syncSuperDiscount" active-text="同步至超级会员" style="margin: 0 8px;"></el-switch>
						<el-tooltip popper-class="el-tooltip-theme-fresh" placement="top" effect="light">
							<div slot="content">
								<p>开启后合作商户参与后，此卡会员群体用户到合作商户消费将按照会员卡折扣享受优惠；</p>
								<p>此活动将默认按照与合作商户关系展示出资方；</p>
							</div>
							<i class="el-icon-question" />
						</el-tooltip>
					</div>
				</el-form-item>

				<!-- 充送规则 -->
				<el-form-item label="充值赠送：">
					<div v-for="(item, index) in form.rechargeAwardInfo" :key="index">
						<el-card class="gift-rights-box">
							<div class="flexRBC">
								<div>规则 {{ index + 1 }}：</div>
								<el-button type="text" @click.prevent="delRules(index)">删除</el-button>
							</div>
							<!-- 类型 -->
							<el-form-item label-width="100px" label="规则类型：">
								<el-radio v-model="item.calculateWay" :label="1">单次充值满额送</el-radio>
								<div class="tips">储值达到设定门槛才送，不累计，可设置多个储值门槛</div>
								<el-radio v-model="item.calculateWay" :disabled="index != 0 && form.rechargeAwardInfo[0].calculateWay === 1" :label="2">每满累计送</el-radio>
								<div class="tips">储值达到设定门槛送，如设定储值100元送10元，则储值200元时候，自动送20元，只可以设置一个储值门槛</div>
							</el-form-item>
							<!-- 充值-->
							<el-form-item :prop="'rechargeAwardInfo.' + index + '.baseAmount'" :rules="rules.baseAmount" label-width="100px" label="充值金额：">
								<el-input v-model="item.baseAmount" maxlength="10" class="input-append-350">
									<template slot="append">
										元
									</template>
								</el-input>
							</el-form-item>

							<!-- 充值赠送  至少存在一种 -->
							<el-form-item
								:prop="'rechargeAwardInfo.' + index + '.rechargeAwardInfoGiftType'"
								:rules="rules.rechargeAwardInfoGiftType"
								label-width="100px"
								label="赠送类型："
							>
								<el-checkbox-group
									v-model="item.rechargeAwardInfoGiftType"
									@change="
										res => {
											return rechargeAwardInfoGiftTypeChange(res, index);
										}
									"
								>
									<el-checkbox label="1" name="rechargeAwardInfoGiftType">返现</el-checkbox>
									<el-checkbox :disabled="item.rechargeAwardInfoGiftType.includes('3')" label="4" name="rechargeAwardInfoGiftType">卡券</el-checkbox>
									<el-checkbox :disabled="item.rechargeAwardInfoGiftType.includes('4')" label="3" name="rechargeAwardInfoGiftType">优惠券(已弃用)</el-checkbox>
									<el-checkbox :disabled="!enablePoints" label="2" name="rechargeAwardInfoGiftType">积分</el-checkbox>
									&nbsp;&nbsp;&nbsp;
									<el-tag v-if="!enablePoints" class="enable-point-tips" style="display:inline-block;margin-left:20px;" type="danger">
										<i class="el-icon-warning" />
										&nbsp;提示：未开启积分功能&nbsp;&nbsp;
										<span class="link app-text-color-primary" @click="goVipPoints"><u>去开启积分功能</u></span>
									</el-tag>
								</el-checkbox-group>
							</el-form-item>
							<!-- 返现金额-->
							<el-form-item
								v-if="item.rechargeAwardInfoGiftType.includes('1')"
								:prop="'rechargeAwardInfo.' + index + (item.giftType === 1 ? '.giftBalance' : '.giftPercent')"
								:rules="item.giftType === 1 ? rules.giftBalance : rules.giftPercentage"
								label-width="100px"
								label="返现金额："
							>
								<el-select v-if="item.giftType === 1" v-model="item.giftType" placeholder="请选择" style="width:170px;display:inline-block">
									<el-option :value="1" label="按照固定金额赠送" />
									<el-option :value="2" :disabled="item.calculateWay === 2" label="按固定百分比赠送" />
								</el-select>
								<el-input v-if="item.giftType === 1" v-model="item.giftBalance" placeholder="请输入" maxlength="10" style="width:176px;vertical-align:top;">
									<template slot="append">
										元
									</template>
								</el-input>

								<el-select v-if="item.giftType === 2" v-model="item.giftType" placeholder="请选择" style="width:170px;display:inline-block">
									<el-option :value="1" label="按照固定金额赠送" />
									<el-option :value="2" :disabled="item.calculateWay === 2" label="按固定百分比赠送" />
								</el-select>
								<el-input v-if="item.giftType === 2" v-model="item.giftPercent" placeholder="请输入" maxlength="3" style="width:176px;vertical-align:top;">
									<template slot="append">
										%
									</template>
								</el-input>
							</el-form-item>

							<!-- 积分 -->
							<el-form-item
								v-if="item.rechargeAwardInfoGiftType.includes('2')"
								:prop="'rechargeAwardInfo.' + index + '.giftPoints'"
								:rules="rules.giftPoints"
								label="赠送积分："
								label-width="100px"
							>
								<el-input v-model="item.giftPoints" maxlength="7" class="input-append-350">
									<template slot="append">
										个
									</template>
								</el-input>
							</el-form-item>

							<!-- 优惠券-->
							<!--              <el-form-item
                v-if="item.rechargeAwardInfoGiftType.includes('3')"
                :prop="'rechargeAwardInfo.' + index + '.couponAwards'"
                :rules="rules.couponAwards"
                label="送优惠券："
                label-width="100px"
              >
                <ul>
                  <li
                    v-for="(couponAwardsItem,couponAwardsIndex) in item.couponAwards"
                    :key="couponAwardsIndex"
                  >
                    <el-card
                      :body-style="{ padding: '0 20px' }"
                      shadow="always"
                      class="el-card-coupon"
                    >
                      <div class="coupon-list">
                        <el-form-item
                          :prop="'rechargeAwardInfo.' + index +'.couponAwards.'+couponAwardsIndex+'.couponId'"
                          :rules="rules.couponAwardId"
                          style="display:inline-block"
                        >
                          <div class="coupon-info">
                            <div>
                              券名：{{ couponAwardsItem.couponName }}
                              <span
                                class="app-text-color-danger"
                              >{{ invalidCouponIds.includes(item.couponId)?'(已失效)':'' }}</span>
                            </div>
                          </div>
                        </el-form-item>
                        <div class="coupon-num">
                          <el-form-item
                            :prop="'rechargeAwardInfo.' + index +'.couponAwards.'+couponAwardsIndex+'.amount'"
                            :rules="rules.couponAwardsAmount"
                            style="display:inline-block"
                          >
                            <el-input-number v-model="couponAwardsItem.amount" :min="1" :max="99"/>&nbsp;&nbsp;张&nbsp;&nbsp;
                          </el-form-item>
                          <el-button
                            type="text"
                            style="display:inline"
                            @click="delCardCoupon(index,couponAwardsIndex)"
                          >删除</el-button>
                        </div>
                      </div>
                    </el-card>
                  </li>
                </ul>
                <el-button
                  :disabled="item.couponAwards.length>=10"
                  type="text"
                  icon="el-icon-plus"
                  style="display:block"
                  @click="openCouponList(index)"
                >增加券</el-button>
                <div style="font-size: 12px;color: #606266">单次最多添加卡券种类不超过10种，卡券总数量不超过30张（因为微信限制，暂不支持配置微信商家券）</div>
              </el-form-item>-->

							<!-- 奖励优惠券 券v2 -->
							<el-form-item
								v-if="item.rechargeAwardInfoGiftType.includes('4') || item.rechargeAwardInfoGiftType.includes('3')"
								:rules="rules.couponAwards"
								:label="item.rechargeAwardInfoGiftType.includes('4') ? '赠送卡券：' : '送优惠券'"
								label-width="100px"
							>
								<div class="card-coupon-container">
									<el-table :data="item.couponAwards" border stripe size="small" empty-text="暂未配置" style="width: 100%">
										<el-table-column prop="couponId" label="批次号" />
										<el-table-column prop="couponName" label="卡券名称" />
										<el-table-column prop="couponType" label="卡券类型">
											<template slot-scope="scope">
												{{ $store.getters.cardCouponTypeKeyOptions[scope.row.couponType] }}
											</template>
										</el-table-column>
										<el-table-column prop="amount" label="数量" width="170px">
											<template slot-scope="scope">
												<el-form-item :prop="'rechargeAwardInfo.' + index + '.couponAwards.' + scope.$index + '.amount'" :rules="rules.couponAwardsAmount">
													<el-input-number v-model="scope.row.amount" :min="1" :max="99" maxlength="2" label="数量" style="margin-top: 18px" />
												</el-form-item>
											</template>
										</el-table-column>
										<el-table-column label="操作" width="80">
											<template slot-scope="scope">
												<el-button type="text" @click="delCardCoupon(index, scope.$index)">删除</el-button>
											</template>
										</el-table-column>
									</el-table>
									<el-button
										v-if="item.rechargeAwardInfoGiftType.includes('4')"
										:disabled="item.couponAwards.length >= 10"
										type="text"
										icon="el-icon-plus"
										style="display:block"
										@click.native.prevent="openDialogCardCouponTable(index)"
									>
										增加卡券
									</el-button>
									<!--<el-button-->
									<!--  v-if="item.rechargeAwardInfoGiftType.includes('3')"-->
									<!--  disabled="false"-->
									<!--  type="text"-->
									<!--  icon="el-icon-plus"-->
									<!--  style="display:block"-->
									<!--  @click="openCouponList(index)"-->
									<!--&gt;增加券-->
									<!--</el-button>-->
									<div style="font-size: 12px;color: #606266">单次最多添加卡券种类不超过10种，卡券总数量不超过30张（因为微信限制，暂不支持配置微信商家券）</div>
								</div>
							</el-form-item>
						</el-card>
					</div>
					<el-button type="text" icon="el-icon-plus" @click="addRules">增加规则</el-button>
				</el-form-item>

				<!-- 消费积分特权 -->
				<el-form-item label="消费积分特权：" prop="multiplePoints">
					<el-radio v-model="form.multiplePointsRadio" :label="1">无倍数</el-radio>
					<br />
					<el-radio v-model="form.multiplePointsRadio" :label="2" :disabled="!enableConsumeBonus">消费享受&nbsp;&nbsp;</el-radio>
					<el-input v-model="form.multiplePoints" :disabled="form.multiplePointsRadio === 1 || !enableConsumeBonus" maxlength="3" class="input-append-150">
						<template slot="append">
							倍积分
						</template>
					</el-input>
					<el-switch v-if="superData.status == 1" v-model="form.syncSuperReward" active-text="同步至超级会员积分奖励" style="margin: 0 8px;"></el-switch>
					<el-tooltip popper-class="el-tooltip-theme-fresh" placement="top" effect="light">
						<div slot="content">
							<p>开启后此卡的超级会员用户去合作商户消费将按照这里设置倍数计算奖励积分，此操作不需要合作商户是否参与，请谨慎操作；</p>
							<p>此活动将默认按照与合作商户关系展示出资方；</p>
						</div>
						<i class="el-icon-question" />
					</el-tooltip>
					<div>
						<el-tag v-if="!enableConsumeBonus" class="enable-point-tips" style="margin-top:10px;" type="danger">
							<i class="el-icon-warning" />
							&nbsp;提示：设置消费积分权益需要开启积分功能和消费积分功能，您还未开启&nbsp;&nbsp;
							<span class="link app-text-color-primary" @click="goVipPoints"><u>去开启积分功能</u></span>
						</el-tag>
					</div>
				</el-form-item>

				<!-- 自定义权益 -->
				<el-form-item label="自定义权益：">
					<div v-for="(item, index) in form.customBenefit" :key="index">
						<el-card class="interests-box-card">
							<div class="flexRBC">
								<div>权益 {{ index + 1 }}：</div>
								<el-button type="text" @click.prevent="delInterests(index)">删除</el-button>
							</div>
							<el-form-item :prop="'customBenefit.' + index + '.value'" :rules="rules.customBenefitValue" label="权益说明：">
								<el-input v-model="item.value" :autosize="{ minRows: 2 }" type="textarea" placeholder="请输入权益说明" />
							</el-form-item>
							<!--              <el-form-item label="权益说明图：">-->
							<!--                <el-upload-->
							<!--                  class="app-uploader-img-plus fl"-->
							<!--                  :action="actionUrl"-->
							<!--                  :show-file-list="false"-->
							<!--                  :headers="uploadHeaders"-->
							<!--                  :on-success="(res,file)=>{return handleAvatarSuccess(res,file,index)}"-->
							<!--                  :before-upload="beforeAvatarUpload"-->
							<!--                >-->
							<!--                  <img v-if="item.imgUrl" :src="fileBaseUrl+item.imgUrl" class="avatar" />-->
							<!--                  <i v-else class="el-icon-plus app-uploader-img-plus-icon"></i>-->
							<!--                </el-upload>-->
							<!--                <ul class="fl upload_tips">-->
							<!--                  <li>图片要求：</li>-->
							<!--                  <li>1.上传的图片大小不超过500KB，仅支持JPG/PNG格式</li>-->
							<!--                  <li>2.像素大小控制在700像素*300像素以下</li>-->
							<!--                </ul>-->
							<!--              </el-form-item>-->
						</el-card>
					</div>
					<el-button type="text" icon="el-icon-plus" @click="addInterests">增加自定义权益</el-button>
				</el-form-item>
				<!-- 特权说明 -->
				<el-form-item label="其它特权说明：" prop="privilege">
					<el-card><el-input v-model="form.privilege" :autosize="{ minRows: 5 }" type="textarea" placeholder="请输入" /></el-card>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button round size="small" @click="hide">取 消</el-button>
				<el-button :disabled="loading" type="primary" round size="small" @click="save">保 存</el-button>
			</span>
		</el-dialog>

		<!-- 券1.0 筛选表格 -->
		<dialog-coupon-list ref="dialogCouponList" />
		<!--券2.0 筛选表格 -->
		<DialogCardCouponTable
			ref="dialogCardCouponTable"
			:card-coupon-type="['cash', 'discount', 'exchange', 'cash_wx_pay', 'times', 'gift']"
			:has-checked-ids="hasCheckedCardCouponIds"
		/>
	</div>
</template>

<script>
import DialogCouponList from '@/components/DialogCouponList';
import DialogCardCouponTable from '@/components/DialogCardCouponTable';
import { imgUploadUrl } from '@/api/upload';
import { mapGetters } from 'vuex';
import { getCardRights, editVipCard } from '@/api/vip';
import { getPointsConfig } from '@/api/points';
import { validateCustomTwoDecimal, validateCustomADecimal, validateCustomPositiveInt, validateStrLen, validateMultiple } from '@/utils/validate';
export default {
	components: {
		DialogCouponList,
		DialogCardCouponTable
	},
	data() {
		/**
		 * 表单校验方法相关
		 */
		// 充值金钱校验
		const validateRmb = (rule, value, callback, text) => {
			if (this.$isNull(value)) {
				callback(new Error(text));
			} else if (!validateCustomTwoDecimal(value, 7)) {
				callback(new Error('请输入0.01~9999999.99'));
			} else {
				callback();
			}
		};

		// 权益折扣
		const validateDiscount = (rule, value, callback) => {
			if (this.form.discountRadio === 1) {
				callback();
			} else if (this.$isNull(value)) {
				callback(new Error('请输入折扣'));
			} else if (!validateCustomADecimal(value, 1)) {
				callback(new Error('请输入正整数（不大于10），或正小数（小数位不超过1位）'));
			} else {
				callback();
			}
		};

		// 积分系数
		const validateMultiplePoints = (rule, value, callback) => {
			if (this.form.multiplePointsRadio === 1) {
				callback();
			} else if (value === '') {
				callback(new Error('请输入积分倍数'));
			} else if (!validateMultiple(value)) {
				callback(new Error('请输入1.1~9.9的数字'));
			} else {
				callback();
			}
		};

		// 权益规则 充值
		const validateBaseAmount = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请输入充值金额'));
			} else if (!validateCustomTwoDecimal(value, 7)) {
				callback(new Error('请输入0.01~9999999.99'));
			} else if (!isBaseAmountRepeat()) {
				callback(new Error('充值金额重复'));
			} else {
				callback();
			}
		};

		// 判断充值金额是否重复
		const isBaseAmountRepeat = () => {
			let baseAmountArray = [];
			this.form.rechargeAwardInfo.forEach((v, i) => {
				baseAmountArray.push(Number(v.baseAmount));
			});
			const oldLength = baseAmountArray.length;
			baseAmountArray = [...new Set(baseAmountArray)]; // 利用SET去重
			const newLength = baseAmountArray.length;
			return oldLength === newLength;
		};

		// 权益规则 返现金额
		const validateGiftBalance = (rule, value, callback) => {
			validateRmb(rule, value, callback, '请输入返现金额');
		};

		// 权益规则 返现比例
		const validateGiftPercentage = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请输入返现比例'));
			} else if (!validateCustomPositiveInt(value, 2, [100])) {
				callback(new Error('请输入1到100的正整数'));
			} else {
				callback();
			}
		};
		// 权益规则 赠送积分
		const validateGiftPoints = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请输入则送积分'));
			} else if (!validateCustomPositiveInt(value, 7)) {
				callback(new Error('请输入正整数'));
			} else {
				callback();
			}
		};

		//  校验优惠券id是否已经过期
		// const validateCouponAwardsId = (rule, value, callback) => {
		//   if (value === '') {
		//     callback('请选择优惠券')
		//   } else if (this.invalidCouponIds.includes(value)) {
		//     callback(new Error('该券已过期或已删除，请更换其它券'))
		//   } else {
		//     callback()
		//   }
		// }

		// 赠送优惠券
		const validateCouponAwardsAmount = (rule, value, callback) => {
			console.log(rule.fullField.replace(/.\d+.amount/, ''));
			if (this.$isNull(value)) {
				callback('请输入数量');
			} else if (!validateCustomPositiveInt(value, 2)) {
				callback(new Error('请输入正整数'));
			} else {
				this.$refs.form.validateField([rule.fullField.replace(/.\d+.amount/, '')]);
				callback();
			}
		};

		// 奖励优惠券
		const validateCouponAwards = (rule, value, callback) => {
			if (!value.length) {
				callback('请至少选择一种');
			} else if (value.length > 10) {
				callback('种类不超过10种');
			} else {
				let maxAmount = 0;
				value.forEach(v => {
					if (validateCustomPositiveInt(v.amount, 2)) {
						maxAmount += v.amount;
					}
				});
				if (maxAmount > 30) {
					callback('总数量不超过30张');
				} else {
					callback();
				}
			}
		};

		// 自定义权益说明校验
		const validateCustomBenefitValue = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请输入自定义权益说明'));
			} else if (!validateStrLen(value, 60)) {
				callback(new Error('长度不超过30个汉字或60个字符'));
			} else {
				callback();
			}
		};

		// 自定义特权说明
		const validatePrivilege = (rule, value, callback) => {
			if (value === '') {
				callback();
			} else if (!validateStrLen(value, 200)) {
				callback(new Error('长度不超过200个汉字或400个字符'));
			} else {
				callback();
			}
		};
		return {
			/**
			 * 表单校验字段相关
			 */
			rules: {
				// 权益折扣
				categoryDiscount: [
					{
						required: true,
						validator: validateDiscount,
						trigger: ['blur', 'change']
					}
				],
				// 积分系数
				multiplePoints: [
					{
						required: true,
						validator: validateMultiplePoints,
						trigger: ['blur', 'change']
					}
				],
				// 充值赠送 充值金额
				baseAmount: [
					{
						required: true,
						validator: validateBaseAmount,
						trigger: ['blur', 'change']
					}
				],
				giftPoints: [
					{
						required: true,
						validator: validateGiftPoints,
						trigger: ['blur', 'change']
					}
				],
				// 充值赠送 返利金额
				giftBalance: [
					{
						required: true,
						validator: validateGiftBalance,
						trigger: ['blur', 'change']
					}
				],
				// 充值赠送 百分比
				giftPercentage: [
					{
						required: true,
						validator: validateGiftPercentage,
						trigger: ['blur', 'change']
					}
				],
				// 充值赠送 固定
				customBenefitValue: [
					{
						required: true,
						validator: validateCustomBenefitValue,
						trigger: ['blur', 'change']
					}
				],
				// 优惠券
				couponAwards: [
					{
						type: 'array',
						required: true,
						validator: validateCouponAwards,
						trigger: ['blur', 'change']
					}
				],
				// 优惠券
				// couponAwardsId: [
				//   {
				//     required: true,
				//     validator: validateCouponAwardsId,
				//     trigger: ['blur', 'change']
				//   }
				// ],
				// 优惠券数量
				couponAwardsAmount: [
					{
						required: true,
						validator: validateCouponAwardsAmount,
						trigger: ['blur', 'change']
					}
				],
				// 如果有充送规则 至少设置一种充送奖励
				rechargeAwardInfoGiftType: [
					{
						type: 'array',
						required: true,
						message: '请至少设置一种充送奖励',
						trigger: 'change'
					}
				],
				privilege: [
					{
						validator: validatePrivilege,
						trigger: ['blur', 'change']
					}
				]
			},
			// 配置
			resolve: null,
			reject: null,
			actionUrl: imgUploadUrl, // 上传地址
			uploadHeaders: {}, // 上传请求头
			// 状态
			dialogVisible: false,
			loading: false,
			enablePoints: true, // 是否开启积分
			enableConsumeBonus: true, // 是否开启消费积分
			// 数据
			id: '',
			name: '',
			hasCheckedCardCouponIds: [], // 当前规则已选择的优惠券
			hasCheckedCardCouponAllIds: [], // 当前所有规则默认已选择的优惠券
			// invalidCouponIds: [], // 失效的优惠券id
			privilege: '',
			form: {
				discountRadio: 1, // 折扣单选状态 not params
				multiplePointsRadio: 1, // 积分倍数单选状态 not params
				categoryDiscount: '', // 折扣
				syncSuperDiscount: false, //同步至超级会员(折扣)
				multiplePoints: '', // 积分倍数 1.1到9.9 需要*10
				syncSuperReward: false, //同步至超级会员积分奖励
				rechargeAwardInfo: [], // 赠送规则
				customBenefit: [], // 自定义权益
				privilege: ''
			}
		};
	},
	computed: {
		...mapGetters(['fileBaseUrl'])
	},
	watch: {
		form: {
			handler: function(val) {
				// 折扣
				if (val.discountRadio === 1) {
					this.$refs.form.clearValidate(['categoryDiscount']);
				}

				// 积分系数
				if (val.multiplePointsRadio === 1) {
					this.$refs.form.clearValidate(['multiplePoints']);
				}

				if (val.rechargeAwardInfo.length >= 1 && val.rechargeAwardInfo[0].calculateWay === 2) {
					this.form.rechargeAwardInfo[0].giftType = 1;
					this.$refs.form.clearValidate(['giftBalance']);
				}
				// 多个切换单选多选 重置
				if (val.rechargeAwardInfo.length >= 2 && val.rechargeAwardInfo[0].calculateWay === 2) {
					this.$confirm('若选择每满累计送只能设置一种规则，其它规则都会被删除，是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
						center: true,
						roundButton: true
					})
						.then(() => {
							this.form.rechargeAwardInfo = [this.form.rechargeAwardInfo[0]];
						})
						.catch(() => {
							this.form.rechargeAwardInfo[0].calculateWay = 1;
						});
				}
			},
			deep: true
		}
	},

	mounted() {},
	methods: {
		/**
		 * 弹框相关
		 */
		open({ id, name = '', privilege = '', superData }) {
			this.id = id;
			this.name = name;
			this.privilege = privilege;
			this.superData = superData;
			this.initData(id);
			this.show();
			return new Promise((resolve, reject) => {
				this.resolve = resolve;
				this.reject = reject;
			});
		},

		show() {
			this.dialogVisible = true;
		},

		close() {
			this.id = '';
			this.name = '';
			this.hasCheckedCardCouponIds = [];
			// this.invalidCouponIds = []
			this.hasCheckedCardCouponAllIds = [];
			this.loading = false;
			this.enablePoints = true;
			this.enableConsumeBonus = true;
			this.$nextTick(() => {
				this.$refs.form.resetFields();
			});
		},

		hide() {
			this.dialogVisible = false;
		},

		/**
		 * 获取数据
		 */
		// 获取权益数据
		initData(id) {
			this.loading = true;
			Promise.all([this.getRights(id), this.checkPointConfig()]).finally(() => {
				this.loading = false;
			});
		},

		getRights(id) {
			return new Promise(resolve => {
				getCardRights(id)
					.then(res => {
						// 重置回表单数据
						this.resetData(res.data);
					})
					.finally(() => {
						resolve();
					});
			});
		},

		// 格式化数据
		resetData(data) {
			const _this = this;
			// 折扣
			data.discountRadio = data.categoryDiscount === 100 ? 1 : 2;
			data.categoryDiscount = data.discountRadio === 2 ? data.categoryDiscount / 10 : '';
			// 积分系数
			data.multiplePointsRadio = data.multiplePoints === 10 ? 1 : 2;
			data.multiplePoints = data.multiplePointsRadio === 2 ? data.multiplePoints / 10 : '';
			// 权益
			data.customBenefit = data.customBenefit === '' ? [] : JSON.parse(data.customBenefit);
			if (data.rechargeAwardInfo.length >= 1) {
				data.rechargeAwardInfo.forEach(function(v, k) {
					v.baseAmount = v.baseAmount / 100;
					v.giftBalance = v.giftBalance / 100;
					v.rechargeAwardInfoGiftType = [];
					// 判断是否有返现
					if (v.giftBalance !== 0 || v.giftPercent !== 0) {
						v.rechargeAwardInfoGiftType.push('1');
					}
					// 判断是否有积分
					if (v.giftPoints !== 0) {
						v.rechargeAwardInfoGiftType.push('2');
					}

					// 判断是否有优惠券
					if (v.couponAwards.length !== 0) {
						let version = 2; // 判断是v1 还是v2
						// const checkedIds = []
						v.couponAwards.some((v, i) => {
							if (i === 0) {
								version = ['CASH', 'DISCOUNT', 'GENERAL'].includes(v.couponType) ? 1 : 2;
								return true;
							}
							// if (val.couponId) {
							//   checkedIds.push(val.couponId)
							// }
						});
						// _this.hasCheckedCardCouponAllIds = checkedIds
						v.rechargeAwardInfoGiftType.push(version === 2 ? '4' : '3');
						// v1 过期校验
						// if (version === 1 && _this.hasCheckedCardCouponAllIds.length > 0) this.initCouponList()
					}
				});
			}
			data.privilege = this.privilege;
			// 同步超级会员
			data.syncSuperDiscount = data.discountSyncToSuperMember;
			data.syncSuperReward = data.multiplePointsSyncToSuperMember;
			this.form = data;
		},

		// 根据ids获取当前优惠券列表
		// initCouponList(resolve) {
		//   let ids = []
		//   ids = this.hasCheckedCardCouponAllIds
		//   getCouponListByIds({ ids })
		//     .then(res => {
		//       if (res.data) {
		//         res.data.forEach(v => {
		//           if (v.status === 3 || v.logicDelete) {
		//             this.invalidCouponIds.push(v.id)
		//           }
		//         })
		//       }
		//     })
		//     .catch(err => {})
		//     .finally(() => {
		//       resolve()
		//     })
		// },

		// 积分配置
		checkPointConfig() {
			return new Promise(resolve => {
				getPointsConfig()
					.then(res => {
						this.enablePoints = res.data.enablePoints;
						this.enableConsumeBonus = res.data.enablePoints && res.data.enableConsumeBonus;
					})
					.catch(err => {})
					.finally(() => {
						resolve();
					});
			});
		},

		// 更新表单数据
		save() {
			const _this = this;
			this.$refs.form.validate(valid => {
				if (valid) {
					const data = JSON.parse(JSON.stringify(this.form));
					// 折扣
					if (data.discountRadio === 1) {
						data.categoryDiscount = 100;
					} else {
						data.categoryDiscount = this.$math.mul(data.categoryDiscount, 10, 0);
					}
					delete data.discountRadio;

					// 积分系数
					if (data.multiplePointsRadio === 1) {
						data.multiplePoints = 10;
					} else {
						data.multiplePoints = this.$math.mul(data.multiplePoints, 10, 0);
					}
					delete data.multiplePointsRadio;
					// 自定义权益
					data.customBenefit = data.customBenefit.length >= 1 ? JSON.stringify(data.customBenefit) : '';

					// 同步超级会员
					data.discountSyncToSuperMember = data.syncSuperDiscount;
					data.multiplePointsSyncToSuperMember = data.syncSuperReward;

					// 充送权益
					if (data.rechargeAwardInfo.length >= 1) {
						data.rechargeAwardInfo.forEach(function(v, k) {
							v.baseAmount = v.baseAmount !== '' ? _this.$math.mul(v.baseAmount, 100, 0) : 0;
							// 判断赠送类型
							// 余额
							if (v.rechargeAwardInfoGiftType.includes('1')) {
								switch (v.giftType) {
									case 1:
										// 固定金额
										v.giftBalance = v.giftBalance !== '' ? _this.$math.mul(v.giftBalance, 100, 0) : 0;
										v.giftPercent = 0;
										break;
									case 2:
										// 百分比赠送
										v.giftBalance = 0;
										break;
								}
							} else {
								v.giftBalance = 0;
								v.giftPercent = 0;
							}

							// 积分
							if (!v.rechargeAwardInfoGiftType.includes('2')) {
								v.giftPoints = 0;
							}

							// 优惠券
							if (!v.rechargeAwardInfoGiftType.includes('3') && !v.rechargeAwardInfoGiftType.includes('4')) {
								v.couponAwards = [];
							}
						});
					}

					const params = {};
					params.id = this.id;
					params.rights = data;
					params.explain = { privilege: data.privilege };
					this.loading = true;
					editVipCard('put', params)
						.then(res => {
							this.$notify({
								title: '成功',
								message: '更新成功',
								type: 'success',
								duration: 2000,
								offset: 40
							});
							this.hide();
							this.resolve && this.resolve();
						})
						.catch(err => {})
						.finally(() => {
							this.loading = false;
						});
				}
			});
		},

		/**
		 *  按钮组
		 */
		// 跳转积分
		goVipPoints() {
			let tabName = '';
			if (!this.enablePoints) {
				tabName = '';
			} else if (!this.enableConsumeBonus) {
				tabName = 'earn';
			}
			this.$router.push({
				name: 'VipPoints',
				params: { tabName }
			});
		},

		// 新增规则
		addRules() {
			if (this.form.rechargeAwardInfo.length != 0 && this.form.rechargeAwardInfo[0].calculateWay == 2) {
				this.$message({
					message: '每满累计送只能设置一种规则',
					type: 'warning'
				});
			} else {
				this.form.rechargeAwardInfo.push({
					rechargeAwardInfoGiftType: [], // 充值赠送类型
					calculateWay: 1,
					couponAwards: [], // 送优惠券
					baseAmount: '', // 充值金额
					giftType: 1, // 赠送类型
					giftBalance: '', // 赠送固定余额
					giftPercent: '' // 赠送百分比
				});
			}
		},

		// 删除规则
		delRules(index) {
			this.form.rechargeAwardInfo.splice(index, 1);
		},

		// 新增优惠券
		openCouponList(index) {
			this.hasCheckedCardCouponIds = [];
			this.form.rechargeAwardInfo[index].couponAwards.forEach(val => {
				this.hasCheckedCardCouponIds.push(val.couponId);
			});
			this.$nextTick(() => {
				this.$refs.dialogCouponList.open(this.hasCheckedCardCouponIds, 1).then(res => {
					this.$refs.form.clearValidate(['rechargeAwardInfo.' + index + '.couponAwards']);
					const params = Object.assign({}, res);
					// const params = {
					//   couponId: res.id,
					//   amount: 1,
					//   couponName: res.couponName
					// }
					this.form.rechargeAwardInfo[index].couponAwards.push(params);
				});
			});
		},

		//  新增优惠券 v2
		openDialogCardCouponTable(index) {
			this.hasCheckedCardCouponIds = [];
			this.form.rechargeAwardInfo[index].couponAwards.forEach(val => {
				this.hasCheckedCardCouponIds.push(val.couponId);
			});
			this.$nextTick(() => {
				this.$refs.dialogCardCouponTable.open().then(res => {
					this.$refs.form.clearValidate(['rechargeAwardInfo.' + index + '.couponAwards']);
					this.form.rechargeAwardInfo[index].couponAwards = this.form.rechargeAwardInfo[index].couponAwards.concat(res);
				});
			});
		},

		// 删除优惠券
		delCardCoupon(index, couponAwardsIndex) {
			this.form.rechargeAwardInfo[index].couponAwards.splice(couponAwardsIndex, 1);
			if (this.form.rechargeAwardInfo[index].couponAwards.length <= 10) {
				this.$refs.form.clearValidate(['rechargeAwardInfo.' + index + '.couponAwards']);
			}
		},

		// 新增权益
		addInterests() {
			this.form.customBenefit.push({
				value: '',
				imgUrl: ''
			});
		},

		// 删除权益
		delInterests(index) {
			this.form.customBenefit.splice(index, 1);
		},

		// 图片上传
		handleAvatarSuccess(res, file, index) {
			if (res.code === 0) {
				this.form.customBenefit[index].imgUrl = res.data.path;
			} else {
				this.$message.error(res.msg);
			}
		},

		// 上传预处理
		beforeAvatarUpload(file) {
			return this.beforeUploadImg(file, this, 700, 300, 0.5);
		},

		/**
		 * 状态组
		 */
		// 优惠券选择改变
		couponSelectChange(index) {
			this.hasCheckedCardCouponIds = [];
			this.form.rechargeAwardInfo[index].couponAwards.forEach(val => {
				if (val.couponId) {
					this.hasCheckedCardCouponIds.push(val.couponId);
				}
			});
		},

		rechargeAwardInfoGiftTypeChange(res, index) {
			if (!res.includes('3') && !res.includes('4')) {
				this.form.rechargeAwardInfo[index].couponAwards = [];
			}
		}
	}
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.content {
	margin: 0 auto;
	min-width: 900px;
	max-width: 1000px;
}

/* input */
.input-append-150 {
	width: 150px;
}
.input-append-350 {
	width: 350px;
}

/* 充送规则卡片 */
.gift-rights-box {
	margin-bottom: 10px;
	.tips {
		font-size: 12px;
		color: #909399;
		line-height: 14px;
	}
}

/* 券列表 */
//.el-card-coupon {
//  width: 100%;
//  margin-bottom: 10px;
//}
//.coupon-list {
//  margin-top: 18px;
//  width: 100%;
//  display: flex;
//  align-items: center;
//  justify-content: space-between;
//  .coupon-info {
//    color: #606266;
//    margin-right: 20px;
//    line-height: 1.2;
//  }
//}

/* 自定义权益卡片 */
.interests-box-card {
	position: relative;
	margin-bottom: 10px;
	.input-with-select .el-select .el-input {
		width: 130px;
	}
	.input-with-select .el-input-group__prepend {
		background-color: #fff;
	}
}

.app-uploader-img-plus {
	width: 300px;
	height: 130px;
	.app-uploader-img-plus-icon {
		font-size: 36px;
		color: #8c939d;
		width: 300px;
		height: 130px;
		line-height: 130px;
		text-align: center;
	}
	.avatar {
		width: 300px;
		height: 130px;
		display: block;
	}
}
.upload_tips {
	margin: 20px 0 0 20px;
	li {
		margin-top: 10px;
		font-size: 14px;
		line-height: 16px;
		color: $dark-font-color;
	}
}

/* 积分提示 */
.enable-point-tips {
	.link {
		cursor: pointer;
	}
}
</style>
